package com.bjtang.fileSync.file;

import java.io.File;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import com.bjtang.fileSync.util.FileConfig;

public class FileMonitor {
	private FileAlterationMonitor monitor;

	private String[] suffixs;

	public FileMonitor(long interval, String suffixs, String path) {
		monitor = new FileAlterationMonitor(interval);
		this.suffixs = suffixs.split(",");
		monitor(path, new FileListener());
	}

	/*
	 * 读取配置文件
	 */
	public FileMonitor() {
		String readConfig = FileConfig.readConfig("timeSize");
		monitor = new FileAlterationMonitor( Long.valueOf(readConfig.trim()));
		this.suffixs = FileConfig.readConfig("suffixs").trim().split(",");
		this.monitor(FileConfig.readConfig("path").trim(),new FileListener());
	}

	public static void main(String[] args) throws Exception {
		// 每两秒监听一次,实际上最好每分钟进行监听
		FileMonitor fileMonitor = new FileMonitor(2000, FileConfig.readConfig("suffixs"),
				FileConfig.readConfig("path"));
		fileMonitor.start();
	}

	/**
	 * 给文件添加监听
	 * 
	 * @param fileListener
	 */
	public void monitor(String path, FileAlterationListener fileListener) {
		// 创建过滤器
		System.out.println("===文件检测开始运行=== ");
		// 文件夹且可以显示的
		IOFileFilter directories = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(), HiddenFileFilter.VISIBLE);
		// 创建文件名过滤器 批量匹配
		PrefixFileFilter suffixFilter = new PrefixFileFilter() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean accept(File file) {
				for (String filter : suffixs) {
					if (file.getName().endsWith("."+filter)) {
						return true;
					}
				}
				return false;
			}
		};
		IOFileFilter filter = FileFilterUtils.or(directories, suffixFilter);
		// 装配过滤器
		FileAlterationObserver observer = new FileAlterationObserver(new File(path), filter);
		monitor.addObserver(observer);
		observer.addListener(fileListener);
	}

	public void stop() throws Exception {
		monitor.stop();
	}

	public void start() throws Exception {
		monitor.start();
	}
}
